//
//  L1DateHelper.m
//  Lesson401
//
//  Created by 徐盟 on 2023/3/17.
//

#import "XMMoment.h"

@implementation XMMoment


- (NSTimeInterval)timestamp
{
    return  [self.date timeIntervalSince1970];
}

- (instancetype)init
{
    if (self = [super init]) {
        self.date = [[NSDate alloc] init];
    }
    return self;
}
+(instancetype) moment
{
    return  [[self alloc] init];
}

- (instancetype)initWithDate:(NSDate *) date
{
    if (self = [super init]) {
        self.date = date;
    }
    return self;
}

+(instancetype) momentWithDate:(NSDate *) date
{
    return  [[self alloc] initWithDate:date];
}
- (instancetype)initWithTimestamp:(NSTimeInterval)timestamp
{
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:timestamp];
   
    if (self = [super init]) {
        self.date = date;
    }
    return self;
}
+ (instancetype)momentWithTimestamp:(NSTimeInterval)timestap
{
    return  [[self alloc] initWithTimestamp:timestap];
}


-(instancetype) initWIthString:(NSString *) str format:( NSString *)format
{
    if (self = [super init]) {
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
            [fmt setDateFormat:format];
        self.date = [fmt dateFromString:str];
    }
    
    return  self;
}
+(instancetype) momentWithString:(NSString *) str format:(NSString *)format
{
    return  [[self alloc] initWIthString:str format:format];
}

- (NSString *)foramt:(NSString *)format
{
    NSDateFormatter * fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = format;
    
    return  [fmt stringFromDate:self.date];
}


-(void) addSecond:(NSInteger) second
{
    NSTimeInterval newStamp = self.timestamp + second;
    self.date = [NSDate dateWithTimeIntervalSince1970:newStamp];
}
-(instancetype) createMomentByAddSecond:(NSInteger) second
{
    NSTimeInterval newStamp = self.timestamp + second;
    
    return [XMMoment momentWithTimestamp:newStamp];
}
-(NSInteger) secondThenOther:(XMMoment *) otherMoment
{
    return  (NSInteger)self.timestamp - otherMoment.timestamp;
}
-(NSDateComponents *) componentsThenOther:(XMMoment *) otherMoment
{
    NSInteger seconds = [self secondThenOther:otherMoment];
    
    NSDateComponents * components = [[NSDateComponents alloc] init];
    NSInteger second = (NSInteger) seconds;
    NSInteger minute = floor(second /60);
    NSInteger hour = floor(second /3660);
    NSInteger day = floor(second /3600/24);
    NSInteger year = floor(second /3600/24/365);
    
    [components setSecond:second];
    [components setMinute:minute];
    [components setHour:hour];
    [components setDay:day];
    [components setYear:year];
    
    return  components;
}

-(NSDate *) toDate
{
    return  self.date;
}

- (NSString *)description
{
    return [self foramt:@"YYYY-MM-dd HH:mm:ss"];
}

@end
